<template>
  <div class="image-loader-container">
    <!-- 先加载占位图片，等原图加载完成后再显示原图，相当于是个图片预加载 -->
    <img v-if="!everythingDone" class="placeholder" :src="placeholder" alt="" />
    <img
      @load="handleLoad"
      @transitionend="handleTransitionEnd"
      :src="src"
      alt=""
      :style="{ opacity: originOpacity, transition: `${duration}ms` }"
    />
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
      required: true,
    },
    duration: { // 原始图片加载完成后，图片淡入的时间
      type: Number,
      default: 500,
    },
  },
  data() {
    return {
      originLoaded: false, //  原图是否加载完成
      everythingDone: false, // 是否一切都尘埃落定了
    };
  },
  computed: {
    originOpacity() {
      return this.originLoaded ? 1 : 0;
    },
  },
  methods: {
    handleLoad() {
      // img元素的load事件
      this.originLoaded = true;
      // setTimeout(() => {
      //   this.everythingDone = true;
      //   this.$emit("load");
      // }, this.duration);
    },
    handleTransitionEnd() {
      this.everythingDone = true;
      this.$emit("load");
    }
  },
};
</script>

<style scoped lang="less">
@import "~@/styles/mixin.less";
.image-loader-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  img {
    .self-fill();
    object-fit: cover;
  }

  .placeholder {
    filter: blur(2vw);
    // 让图片模糊化，模拟图片加载过程
  }
}
</style>
